<template>
    <div id="cesium-container">
        <div id="echarts-container"></div>
    </div>
</template>
  
<script>
import * as echarts from 'echarts'
export default {
    name: 'ProfileAnalyse',
    components: {},
    mounted() {
        this.initViewer()
    },
    methods: {
        async initViewer() {
            Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzM2RjYjJlOC01ZTQwLTQwODYtOTEwMy02M2U4OGEzYjQyNGUiLCJpZCI6MjI5NjUsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1ODI0NTYwMzF9.VG2_T9ry8EnBWAh4msJ3s6m2jW_5hgAZQvfEQDh-WQs"
            window.viewer = new window.Cesium.Viewer("cesium-container", {
                terrainProvider: new window.Cesium.CesiumTerrainProvider({
                    url: 'http://data.mars3d.cn/terrain',
                    requestWaterMask: true,
                    requestVertexNormals: true
                }),
                imageryProvider: new window.Cesium.ArcGisMapServerImageryProvider({
                    url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
                }),
                sceneMode: window.Cesium.SceneMode.SCENE3D,
                vrButton: false,
                animation: false,
                baseLayerPicker: false,
                geocoder: false,
                timeline: false,
                fullscreenButton: false,
                homeButton: false,
                creditContainer: document.createElement('div'),
                infoBox: false,
                navigationHelpButton: false,
                sceneModePicker: false,
                scene3DOnly: true,
                skyBox: new window.Cesium.SkyBox({
                    sources: {
                        positiveX: require('@/assets/images/tycho2t3_80_px.jpg'),
                        negativeX: require('@/assets/images/tycho2t3_80_mx.jpg'),
                        positiveY: require('@/assets/images/tycho2t3_80_py.jpg'),
                        negativeY: require('@/assets/images/tycho2t3_80_my.jpg'),
                        positiveZ: require('@/assets/images/tycho2t3_80_pz.jpg'),
                        negativeZ: require('@/assets/images/tycho2t3_80_mz.jpg'),
                    }
                })
            });
            window.viewer.scene.globe.depthTestAgainstTerrain = true;

            let startAndEndPoints = [], interNumber = 5000
            const handler = new window.Cesium.ScreenSpaceEventHandler(window.viewer.scene.canvas);
            handler.setInputAction(function (movement) {
                startAndEndPoints.push(window.viewer.scene.pickPosition(movement.position))
                if (startAndEndPoints.length == 2) {
                    var profile = {
                        arrHB: [],
                        arrPoint: [],
                        arrLX: [],
                        ponits: [],
                        distance: 0
                    }
                    for (let i = 0; i < startAndEndPoints.length - 1; i++) {
                        var point = equidistantInterpolation(startAndEndPoints[i], startAndEndPoints[i + 1])
                        profile.arrPoint.push(point)
                    }
                    for (var j = 0; j < profile.arrPoint.length; j++) {
                        for (var m = 0; m < profile.arrPoint[j].length; m++) {
                            profile.ponits.push(profile.arrPoint[j][m])
                        }
                    }
                    profile.arrLX.push(0)
                    for (var k = 1; k < profile.ponits.length - 1; k++) {
                        profile.arrHB.push(profile.ponits[k].hit)
                        var disc = distance(profile.ponits[k - 1], profile.ponits[k])
                        profile.distance = profile.distance + disc
                        profile.arrLX.push(profile.arrLX[k - 1] + disc)
                    }
                    console.log(profile)
                    initChart(profile)
                    startAndEndPoints = []
                }
            }, window.Cesium.ScreenSpaceEventType.LEFT_CLICK);

            function equidistantInterpolation(pointA, pointB) {
                // 插值处理
                var tpLength = getArcLength(pointA, pointB)
                // 插值间距按照输入的插值来进行
                var interpolationNumber = parseInt(tpLength / interNumber)
                var pointAToW84 = worldCoordinateToLonAndLat(pointA)
                var pointBToW84 = worldCoordinateToLonAndLat(pointB)
                var lat1 = window.Cesium.Math.toRadians(pointAToW84.lat)
                var lon1 = window.Cesium.Math.toRadians(pointAToW84.lon)
                var lat2 = window.Cesium.Math.toRadians(pointBToW84.lat)
                var lon2 = window.Cesium.Math.toRadians(pointBToW84.lon)
                var spaceList = []
                // 插值坐标数组
                for (var i = 0; i < interpolationNumber + 1; i++) {
                    var lonRadians = window.Cesium.Math.lerp(lon1, lon2, i / interpolationNumber)
                    var latRadians = window.Cesium.Math.lerp(lat1, lat2, i / interpolationNumber)
                    var lon = window.Cesium.Math.toDegrees(lonRadians)
                    var lat = window.Cesium.Math.toDegrees(latRadians)
                    // 计算插值点坐标
                    var point = {
                        lon: Number(lon),
                        lat: Number(lat)
                    }
                    point = getGeoCoordinate(point.lat, point.lon)
                    point.len = 0
                    spaceList.push(point)
                }
                return spaceList
            }

            function getArcLength(pointA, pointB) {
                var lat1 = pointA.x
                var lon1 = pointA.y
                var lat2 = pointB.x
                var lon2 = pointB.y

                var EARTH_RADIUS = 6378137.0
                var PI = Math.PI

                // 弧度
                function getRad(d) {
                    return d * PI / 180.0
                }

                var f = getRad((lat1 + lat2) / 2)
                var g = getRad((lat1 - lat2) / 2)
                var l = getRad((lon1 - lon2) / 2)

                var sg = Math.sin(g)
                var sl = Math.sin(l)
                var sf = Math.sin(f)

                var s, c, w, r, d, h1, h2
                // 地球半径
                var a = EARTH_RADIUS
                // 地球扁率
                var fl = 1 / 298.257

                sg = sg * sg
                sl = sl * sl
                sf = sf * sf

                s = sg * (1 - sl) + (1 - sf) * sl
                c = (1 - sg) * (1 - sl) + sf * sl

                w = Math.atan(Math.sqrt(s / c))
                r = Math.sqrt(s * c) / w
                d = 2 * w * a
                h1 = (3 * r - 1) / 2 / c
                h2 = (3 * r + 1) / 2 / s
                return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg))
            }

            function worldCoordinateToLonAndLat(cartesian3) {
                const cartographic = window.Cesium.Cartographic.fromCartesian(cartesian3)
                const lat = window.Cesium.Math.toDegrees(cartographic.latitude)
                const lng = window.Cesium.Math.toDegrees(cartographic.longitude)
                const alt = cartographic.height
                return { lon: lng, lat: lat, hit: alt }
            }

            function getGeoCoordinate(lat, lon) {
                var terrainheight = window.viewer.scene.globe.getHeight(window.Cesium.Cartographic.fromDegrees(lon, lat));
                (terrainheight !== undefined) ? terrainheight : 0
                var point = {
                    lon: lon,
                    lat: lat,
                    hit: terrainheight
                }
                return point
            }

            function distance(point1, point2) {
                /** 根据经纬度计算出距离**/
                var strat = window.Cesium.Cartographic.fromDegrees(point1.lon, point1.lat, point1.hit)
                var end = window.Cesium.Cartographic.fromDegrees(point2.lon, point2.lat, point2.hit)
                var geodesic = new window.Cesium.EllipsoidGeodesic()
                geodesic.setEndPoints(strat, end)
                var s = geodesic.surfaceDistance
                // 返回两点之间的距离
                s = (Math.sqrt(Math.pow(s, 2) + Math.pow(strat.height - end.height, 2))) / 1000
                // s = Math.abs(strat.height - end.height) / 1000
                return s
            }

            function initChart(e) {
                function strFormat(str) {
                    var strString = String(str)
                    var strs = strString.slice(0, strString.indexOf('.') + 3)
                    return strs
                }
                var t = e.ponits
                var chartData = {
                    dataZoom: [{
                        type: 'inside',
                        throttle: 50
                    }],
                    valueAxis: {
                        position: 'left',
                        axisLine: { // 坐标轴线
                            show: true, // 默认显示，属性show控制显示与否
                            lineStyle: { // 属性lineStyle控制线条样式
                                color: '#48b',
                                width: 2,
                                type: 'solid'
                            }
                        }
                    },
                    grid: {
                        x: 50,
                        y: 40,
                        x2: 80,
                        y2: 40,
                        backgroundColor: 'rgba(0,0,0,0)',
                        borderWidth: 1,
                        borderColor: '#ccc'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (e) {
                            // console.log(e, 'kkkkk')
                            var a = ''
                            if (e.length === 0) return a
                            e[0].value
                            var r = t[e[0].dataIndex]
                            // console.log(r, 'shujuchakan')
                            return a += '所在位置&nbsp;' + strFormat(r.lon) + ',' + strFormat(r.lat) + '</label><br />' + e[0].seriesName + '&nbsp;' + strFormat(r.hit) + "&nbsp;<label style='color:" + e[0].color + ";'>"
                        }
                        /*  */
                    },
                    xAxis: [{
                        name: '距离[km]',
                        // nameLocation: 'left',
                        type: 'category',
                        boundaryGap: false,
                        axisLine: {
                            show: true,
                            symbol: ['none', 'arrow'], // 是否显示轴线箭头
                            symbolSize: [6, 6], // 箭头大小
                            symbolOffset: [0, 7], // 箭头位置
                            lineStyle: {
                                width: 1,
                                type: 'solid'
                            }
                        },
                        axisTick: { // 坐标轴刻度
                            show: true, // 是否显示
                            inside: false, // 是否朝内
                            length: 3, // 长度
                            lineStyle: { // 默认取轴线的样式
                                width: 1,
                                type: 'solid'
                            }
                        },
                        axisLabel: {
                            show: true,
                            interval: 'auto'
                            // formatter:
                        },
                        data: e.arrLX

                    }],
                    yAxis: [{
                        name: '高程值[m]',
                        type: 'value',
                        axisLabel: {
                            rotate: 30,
                            interval: '50'
                        },
                        axisLine: { // 坐标轴 轴线
                            show: true, // 是否显示
                            symbol: ['none', 'arrow'], // 是否显示轴线箭头
                            symbolSize: [6, 6], // 箭头大小
                            symbolOffset: [0, 7], // 箭头位置
                            lineStyle: {
                                width: 1,
                                type: 'solid'
                            }
                        },
                        axisTick: { // 坐标轴刻度
                            show: true, // 是否显示
                            inside: false, // 是否朝内
                            length: 3, // 长度
                            lineStyle: { // 默认取轴线的样式
                                width: 1,
                                type: 'solid'
                            }
                        }

                    }],
                    series: [{
                        name: '高程值',
                        type: 'line',
                        smooth: !0,
                        symbol: 'none',
                        sampling: 'average',
                        zlevel: 1,
                        z: 1,
                        itemStyle: {
                            color: 'rgb(255, 70, 131)'
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgb(255, 158, 68)'
                            },
                            {
                                offset: 1,
                                color: 'rgb(255, 70, 131)'
                            }])

                        },
                        data: e.arrHB
                    }]
                }
                echarts.init(document.getElementById("echarts-container")).setOption(chartData)
            }
        }
    }
}
</script>
  
<style>
#cesium-container {
    width: 100%;
    height: 100%;
}

#echarts-container {
    position: absolute;
    z-index: 10;
    width: 800px;
    height: 250px;
    background-color: aquamarine;
}
</style>
  